#include <lcd.h>
#include <lcd_control.h>
#include <string.h>
#include <delay.h>
#include <gpdr.h>
#include <stdio.h>

int first_time=1;                                          

void lcd_display_date(){
    unsigned char rtc_msg[7];
    unsigned char ymdhms[6];
    unsigned char h,m,s;       
    
    rtc_read(rtc_msg);
    rtc2ymdhms(rtc_msg, ymdhms);
    
    h = ymdhms[3];
    m = ymdhms[4];
    s = ymdhms[5];

    if(first_time || s == 0) {
        lcd_clear_row(0);
        display_date_hms(h,'h');
        lcd_putchar(':');
        display_date_hms(m,'m');      
        lcd_putchar(':');
        display_date_hms(s,'s');
        first_time=0;
    }
    else{
        if(s%2 == 1) lcd_put_char_at(' ',5,0);
        else lcd_put_char_at(':',5,0);
        display_date_hms(s,'s');
    }
}

void display_date_hms(char hms, char type){
    int i, disp;
    switch(type){
        case 'h':lcd_gotoxy(0,0);break;
        case 'm':lcd_gotoxy(3,0);break;
        case 's':lcd_gotoxy(6,0);break;
    }
    for(i=10; i>=1; i/=10){
        disp=hms/i+48;
        lcd_putchar(disp);
        hms%=i;
    }
    
} 

void lcd_clear_row(int row){
    int i;      
    lcd_gotoxy(row,0);
    for(i = 0; i < 16; i++){
        lcd_putchar(' ');
    }   
    lcd_gotoxy(row,0);
}

void lcd_put_char_at(unsigned char c, unsigned char x, unsigned char y){
    lcd_gotoxy(x,y);
    lcd_putchar(c);
}       
 
void lcd_display_status(flash unsigned char* status){  
    lcd_gotoxy(9,0);
    lcd_putsf(status);  
}
    
/*         




void lcd_write_str(unsigned char* str){
    lcd_puts(str);
}                                        

void lcd_write_data_as_number(unsigned char c){
    int j;
    unsigned char s1, s2;
    s1 = c;
    for(j = 100; j >= 1; j/=10){
        s2=s1/j;
        if(s2!=0){
            s2+=+48;
            lcd_putchar(s2);
        }
        s1=s1%j;      
    }     
}

void lcd_write_array(unsigned char* str){
    int i;
    lcd_clear_row(1);
    for(i=0; i < strlen(str); i++){
         lcd_putchar(str[i]);
         lcd_putchar(' ');
         delay_ms(200); 
    }
}

void lcd_write_array_as_number(unsigned char* str){
    int i,j;
    unsigned char s1, s2;
    lcd_clear_row(1);
    for(i=0; i < strlen(str); i++){
        s1 = str[i];
        for(j = 100; j >= 1; j/=10){
            s2=s1/j+48;
            lcd_putchar(s2);
            s1=s1%j;      
        }
        lcd_putchar(' ');
        if(i == 2){
            delay_ms(1000);
            lcd_clear_row(1);
        }
    }
}
*/